package cnisetup

import (
	"context"

	"github.com/f5devcentral/f5-bigip-rest-go/utils"
	"github.com/google/uuid"
	"k8s.io/apimachinery/pkg/runtime"
	"sigs.k8s.io/controller-runtime/pkg/client"

	ctrl "sigs.k8s.io/controller-runtime"
)

type NodeReconciler struct {
	client.Client
	Scheme   *runtime.Scheme
	LogLevel string
	CNIConf  *CNIConfig
}

func (r *NodeReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
	lctx := context.WithValue(ctx, utils.CtxKey_Logger, utils.NewLog().WithRequestID(uuid.New().String()).WithLevel(r.LogLevel))
	slog := utils.LogFromContext(lctx)
	slog.Infof("node event: %s", req.Name)

	return ctrl.Result{}, HandleNodeChanges(CNIContext{Context: lctx, CNIConfig: *r.CNIConf})
}

func HandleNodeChanges(cnictx CNIContext) error {
	var ocfgs map[string]interface{}
	var ncfgs map[string]interface{}
	var err error

	slog := utils.LogFromContext(cnictx.Context)
	bc := cnictx.NewBC()
	// k8scni := cnictx.NewK8SCNI()

	if ocfgs, err = cnictx.GatherSubs(); err != nil {
		return err
	}

	if ncfgs, err = cnictx.ConvertSubs(); err != nil {
		return err
	}
	// if ncfgs, err = k8scni.nodeConfigs(); err != nil {
	// 	return err
	// }

	if err := deploy(bc, "Common", &map[string]interface{}{"": ocfgs}, &map[string]interface{}{"": ncfgs}); err != nil {
		slog.Errorf("failed to do deployment: %s", err.Error())
		return err
	}
	return nil
}
